package com.sunfeng.netty.heima.day01.noblocking;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

import static com.sunfeng.netty.heima.utils.ByteBufferUtil.debugRead;

/**
 * @ClassName NioServerSocket
 * @Description TODO
 * @Author 孙峰
 * @Date 2022/10/24 10:57
 */
@Slf4j

public class NioServerSocket {
    public static void main(String[] args) throws IOException {
        // 使用 nio 来理解非阻塞模式, 单线程
        // 0. ByteBuffer
        ByteBuffer buffer = ByteBuffer.allocate(16);

        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        ssc.bind(new InetSocketAddress(8080));
// 3. 连接集合
        List<SocketChannel> channels = new ArrayList<>();
        while (true) {
            SocketChannel sc = ssc.accept();
            log.debug("connecting.. ..{}", sc); // 其实这里一直在空轮训
            if (ObjectUtil.isNotEmpty(sc)) {
                log.debug("connected .. ..{}", sc);
                //s 设置非阻塞
                sc.configureBlocking(false);
                channels.add(sc);
            }
            for (SocketChannel socketChannel : channels) {
                int read = socketChannel.read(buffer);
                if(read>0){
                    buffer.flip();
                    debugRead(buffer);
                    buffer.clear();
                    log.debug("after read ... {}",channels);
                }
            }
        }

    }
}
